package com.quyeying.config.interceptor;

import com.quyeying.annotation.PassToken;
import com.quyeying.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @ClassName AdminInterceptor
 * @Description TODO
 * @Author skx
 * @Date 2020/11/26
 */
public class AdminInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class) || handlerMethod.getBeanType().isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(ObjectUtils.isEmpty(passToken)) {
                passToken = handlerMethod.getBeanType().getAnnotation(PassToken.class);
            }
            if(passToken.isNeed()) {
                return true;
            }
        }

        //统一拦截（验证是否带有token, token是否合法)
        String authorization = request.getHeader("Authorization");
        //访问表示weChat
        String identity = request.getHeader("identity");
        if(StringUtils.isEmpty(authorization) || StringUtils.isEmpty(identity) || !accessVerification(identity)) {
            returnJson(response,"{\"code\":403,\"msg\":\"非法请求!\"}");
            return false;
        }

        //验证redis里是否存在Token
        Object token = redisUtil.get(authorization);
        if(!StringUtils.isEmpty(token)) {
            return true;
        }

        returnJson(response,"{\"code\":403,\"msg\":\"Invalid Token!\"}");
        return false;
    }

    /*返回客户端数据*/
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
//         System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

    /**
     * 访问检验
     * @return
     */
    public boolean accessVerification(String access){
        if("weChat".equals(access)){
            return true;
        }
        if("ios".equals(access)){
            return true;
        }
        if("android".equals(access)){
            return true;
        }
        return false;
    }
}
